package com.resifind.www.dao.impl;

import com.resifind.www.dao.UserDao;
import com.resifind.www.dao.mapper.Mappers;
import com.resifind.www.po.User;
import com.resifind.www.util.JdbcUtils;

import java.sql.*;
import java.util.List;

/**
 * @author 36069
 */
public class UserDaoImpl implements UserDao {

    @Override
    public int addUser(User user, Connection conn) throws SQLException {
        //language=MySQL
        String sql = "insert into resi_find.user (phone_num, password_hash, salt) values(?, ?, ?)";
        PreparedStatement pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        pst.setString(1, user.getPhoneNum());
        pst.setString(2, user.getHasePassword());
        pst.setString(3, user.getSalt());
        //执行插入语句
        int i = pst.executeUpdate();
        if (i == 1) {
            //获取自增主键
            ResultSet rs = pst.getGeneratedKeys();
            if (rs.next()) {
                //获取自增主键的值
                return rs.getInt(1);
            }
        }
        return -1;
    }

    @Override
    public User queryUser(String phoneNum) {
        //language=MySQL
        String sql = "select * from resi_find.user where phone_num = ?";
        Object[] params = {phoneNum};
        //查询用户列表
        List<User> users = Mappers.userMapper(sql, params);
        return users.isEmpty() ? null : users.getFirst();
    }

    @Override
    public String queryUserTypeById(int id) {
        //language=MySQL
        String sql = "select 'client' as user_type from resi_find.client where user_id = ?" +
                " union all " +
                "select 'merchant' as user_type from resi_find.merchant where user_id = ?";
        Object[] params = {id, id};
        //查询用户类型列表
        List<String> userTypeList = JdbcUtils.query(sql, params, rs ->
                rs.getString("user_type"));
        return userTypeList.isEmpty() ? null : userTypeList.getFirst();
    }

    @Override
    public boolean updatePassword(int userId, String hashPassword, String salt, Connection conn) {
        //language=MySQL
        String sql = "update resi_find.user set password_hash = ?, salt = ? where id = ?";
        Object[] params = {hashPassword, salt, userId};
        return JdbcUtils.update(sql, params, conn);
    }
}
